const fs = require('fs');
const path = require('path');
const koa = require('koa');
const logger = require('koa-logger');
const serve = require('koa-static');
const views = require('koa-views');
const favicon = require('koa-favicon');
const Keygrip = require('keygrip');
const router = require('./router.js');

const app = new koa();

app.keys = Keygrip(['im a newer secret', 'i like turtle']);

app.use(logger());

app.use(favicon('favicon.ico'));
app.use(serve('public'));

app.use(views(path.join(__dirname, 'views'), {map: { hbs: 'handlebars' }}));

app.use(router.routes());

app.use(async function (ctx, next) {
  try {
    await next();
    if (ctx.status === 404) {
      switch (ctx.accepts('html', 'json', 'css')) {
        case 'html':
          ctx.type = 'html';
          ctx.body = fs.readFileSync('views/pages/404.html');
          break;
        case 'json':
          ctx.body = {
            status: -9,
            message: 'bad request',
            path: ctx.request.url
          };
          break;
        default:
          ctx.status = 404;
      }
    }
  } catch (err) {
    ctx.body = {
      message: err.message
    };
    ctx.status = err.status || 500;
  }
});

app.on('error', function (err) {
  console.error('server error', err);
});

app.listen(5555, function () {
  console.log('server listening on port 5555.\n');
});
